package db_main

import (
	"errors"
	"fmt"
	"gorm.io/gorm"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql"
	"longmen/server/pkg/db/mysql/models/models_main"
)

func GetUserCheckinHistory(param map[string]interface{}, page, size int) ([]models_main.UserCheckinHistory, error) {
	fName := "GetUserCheckinHistory"
	var o []models_main.UserCheckinHistory
	table := mysql.GetRTable(&models_main.UserCheckinHistory{})
	mysql.Condition(table, param, "", "", page, size)
	err := table.Order("checkin_time desc").
		Find(&o).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return o, err
}

func InsertUserCheckinHistory(session *gorm.DB, history *models_main.UserCheckinHistory) error {
	fName := "InsertUserCheckinHistory"
	err := session.Create(history).Error
	if err != nil {
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return nil
}

func GetUserCheckinHistoryWeek(uid int) ([]models_main.UserCheckinHistory, error) {
	fName := "GetUserCheckinHistoryByUidOrd"
	var o []models_main.UserCheckinHistory
	err := mysql.GetRTable(&models_main.UserCheckinHistory{}).Where("uid = ? and checkin_time >= date_sub(now(), interval 1 week)", uid).
		Order("checkin_time desc").
		Find(&o).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return o, err
}
